import 'package:flutter/material.dart';
import 'package:stacked/stacked.dart';
import 'package:vista/shared/models/group_message.dart';
import 'package:vista/shared/models/group_snapshot.dart';
import 'package:vista/shared/models/user_frame.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/services/circle_gallery.dart';

/// 群聊视图模型
/// 管理群聊页面的数据和状态
class GroupChatViewModel extends BaseViewModel {
  final AuthFocus _authFocus;
  final CircleGallery _circleGallery;
  final String groupId;

  GroupChatViewModel(this._authFocus, this._circleGallery, this.groupId);

  UserFrame? _currentUser;
  UserFrame? get currentUser => _currentUser;

  GroupSnapshot? _currentGroup;
  GroupSnapshot? get currentGroup => _currentGroup;

  List<GroupMessage> _messages = [];
  List<GroupMessage> get messages => _messages;

  List<UserFrame> _members = [];
  List<UserFrame> get members => _members;

  final TextEditingController _messageController = TextEditingController();
  TextEditingController get messageController => _messageController;

  /// 初始化数据
  Future<void> initialize() async {
    setBusy(true);
    try {
      _currentUser = await _authFocus.getCurrentUser();
      if (_currentUser == null) {
        setBusy(false);
        return;
      }

      _currentGroup = await _circleGallery.getGroupById(groupId);
      await _loadMessages();
      await _loadMembers();
    } finally {
      setBusy(false);
    }
  }

  /// 加载群组消息列表
  Future<void> _loadMessages() async {
    if (_currentUser == null || _currentGroup == null) return;

    _messages = await _circleGallery.getGroupMessages(groupId);
    notifyListeners();
  }

  /// 加载群组成员列表
  Future<void> _loadMembers() async {
    if (_currentUser == null || _currentGroup == null) return;

    final memberIds = await _circleGallery.getGroupMembers(groupId);
    final allUsers = await _authFocus.getUsers();
    _members = allUsers.where((user) => memberIds.contains(user.id)).toList();
    notifyListeners();
  }

  /// 发送文本消息
  Future<void> sendMessage() async {
    if (_currentUser == null || _currentGroup == null) return;
    final content = _messageController.text.trim();
    if (content.isEmpty) return;

    await _circleGallery.sendMessage(
      groupId: groupId,
      userId: _currentUser!.id,
      content: content,
    );

    _messageController.clear();
    await _loadMessages();
    notifyListeners();
  }

  /// 发送拨打失败消息（群聊中暂时不支持，预留接口）
  Future<void> sendCallFailed() async {
    // 群聊暂不支持拨打失败消息
    return;
  }

  /// 获取消息发送者的用户信息
  Future<UserFrame?> getSenderUser(String senderId) async {
    final allUsers = await _authFocus.getUsers();
    try {
      return allUsers.firstWhere((user) => user.id == senderId);
    } catch (e) {
      return null;
    }
  }

  /// 删除当前用户在群组的所有消息
  Future<void> deleteAllMessages() async {
    if (_currentUser == null) return;

    await _circleGallery.deleteAllGroupMessages(groupId);

    await _loadMessages();
    notifyListeners();
  }

  /// 退出群组
  Future<void> leaveGroup() async {
    if (_currentUser == null) return;

    await _circleGallery.leaveGroup(groupId, _currentUser!.id);
    notifyListeners();
  }

  @override
  void dispose() {
    _messageController.dispose();
    super.dispose();
  }
}
